package com.zhuo.delivery.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuo.delivery.common.CustomException;
import com.zhuo.delivery.entity.Category;
import com.zhuo.delivery.entity.Dish;
import com.zhuo.delivery.entity.Setmeal;
import com.zhuo.delivery.mapper.CategoryMapper;
import com.zhuo.delivery.service.CategoryService;
import com.zhuo.delivery.service.DishService;
import com.zhuo.delivery.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    DishService dishService;

    @Autowired
    SetmealService setmealService;

    /**
     * 根据id删除分类，删除之前进行判断，当前分类是否关联菜品，若已经关联，抛出业务异常
     * @param id
     */
    @Override
    public void remove(Long id) {
        //查询当前分类是否关联了菜品，若已关联，则抛出一个业务异常
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
        long dishCount = dishService.count(dishLambdaQueryWrapper);
        if (dishCount>0){
            //已经关联菜品，抛出业务异常
            throw new CustomException("当前分类下关联菜品，无法删除");
        }

        //查询当前分类是否关联了套餐，若已关联，则抛出一个业务异常
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        long setmealCount = setmealService.count(setmealLambdaQueryWrapper);
        if (setmealCount>0){
            //已经关联套餐，抛出业务异常
            throw new CustomException("当前分类下关联套餐，无法删除");
        }

        //正常删除
        super.removeById(id);
    }
}
